(ns net.marigolda.gui-utils
   (:use [net.cgrand.enlive-html :as html]
         [ring.util.response :only [response]]))

;; Utils
(defmacro maybe-substitute
  ([expr] `(if-let [x# ~expr] (html/substitute x#) identity))
  ([expr & exprs] `(maybe-substitute (or ~expr ~@exprs))))

(defmacro maybe-content
  ([expr] `(if-let [x# ~expr] (html/content x#) identity))
  ([expr & exprs] `(maybe-content (or ~expr ~@exprs))))

(defn render [t]
  (apply str t))

(defn render-snippet [s]
  (apply str (html/emit* s)))

(def render-to-response
  (comp response render))

(defn render-request [afn & args]
  (fn [req] (render-to-response (apply afn args))))

;; Wrappers
(def li-wrapper
  (wrap :li))
(def ul-wrapper
  (wrap :ul))
(def h4-wrapper
  (wrap :h4))

(defn to-list [a] (map li-wrapper a))

(defn make-ul [elements]
  "Takes coll and makes html unordered list with coll's elements."
  (ul-wrapper (map li-wrapper elements)))

(defn make-ul-with-h4 [h4 elements]
  (merge [(h4-wrapper h4) (make-ul elements)]))

;;formatters
(defn ratio-formatter [x]
  "Rounding ratio numbers at two decimal spaces (but no zeros at end). Returns string."
  (let [f (str (format "%.2f" (double x)))]
    (cond (.endsWith f ".00") (subs f 0 (.indexOf f "."))
          (.endsWith f "0") (apply str (drop-last f))
          :else
          f)))

;;filters
(defn name-autocomplete-filter [v us]
  (filter (fn [u] (if (some #(.startsWith % v) (.split (if-let [s (:name u)] s "") " ")) true false))  us))
  